import '../lib/jquery.js'
import { $messageTip, $axios } from './util.js'

const axios = $axios();


// 用户登录
function loginUser() {
  const username = $('.username').val();
  const password = $('.password').val();

  if (username === '' || password === '') {
    $messageTip('用户名或密码不能为空！');
    return;
  }

  const data = JSON.stringify({
    username: username,
    password: password
  });

  axios.post('/users/login', data, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    if (response.data) {
      const responseData = JSON.parse(response.data);
      if (responseData.code === 1) {
        sessionStorage.setItem('frontToken', responseData.token);
        sessionStorage.setItem('frontUserInfo', JSON.stringify(responseData.user));
        window.location.href = './index.html';
      } else {
        $messageTip(responseData.message);
      }
    }
  })
}

$('button').on('click', function () {
  loginUser();
});
